package ferp.android.tasks.center;

import android.content.Context;
import android.os.AsyncTask;
import ferp.android.managers.ProfileManager;
import ferp.center.client.Action;
import ferp.center.network.RequestReportGet;
import ferp.center.network.ResponseReportGet;
import ferp.core.game.Game;
import ferp.core.game.Settings;
import ferp.core.log.Log;
import ferp.core.player.Profile;
import ferp.core.state.State;

/**
* User: olegs
* Date: 2/6/13 4:25 PM
*/
public class TaskProfileImport extends AsyncTask<Void, Void, ResponseReportGet>
{
  public interface Listener
  {
    void onProfileImported(boolean success);
  }

  public TaskProfileImport(Context context, Listener listener, long reportID, boolean fromCurrentPosition)
  {
    this.context = context;
    this.listener = listener;
    this.reportID = reportID;
    this.fromCurrentPosition = fromCurrentPosition;
  }

  @Override
  protected ResponseReportGet doInBackground(Void... voids)
  {
    try
    {
      RequestReportGet request = new RequestReportGet();
      request.id = reportID;

      ResponseReportGet response = Action.execute(Action.GAME_REPORT_GET, request, ResponseReportGet.class);

      if (response != null)
      {
        ProfileManager pm = ProfileManager.instance(null);
        String nickname = String.valueOf(reportID);

        // delete profile with such name if exists
        pm.deleteProfile(nickname);

        // create new profile
        Profile p = pm.newCurrentProfile();

        p.nickname = nickname;
        p.settings = Game.gson.fromJson(response.settings, Settings.class);
        p.setStatistics(Game.gson.fromJson(response.statistics, ferp.core.game.Statistics.class));
        p.importGame(Game.gson.fromJson(response.snapshot, Profile.Games.class), response.version);

        // set the proper starting state
        p.game().set(fromCurrentPosition ? State.resume : State.replay);

        // prevent update of the original profile
        p.useCenter = false;
        p.centerId = 0;

        //p.settings.orientation = Settings.Orientation.PORTRAIT;

        // save
        pm.saveCurrentProfile(false);

        return response;
      }
    }
    catch (Exception e)
    {
      Log.error(Action.TAG, e);
    }

    return null;
  }

  @Override
  protected void onPostExecute(ResponseReportGet response)
  {
    listener.onProfileImported(response != null);
  }

  private final Context context;
  private final Listener listener;
  private final long reportID;
  private final boolean fromCurrentPosition;
}
